package mx.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import mx.entity.Company;
import mx.entity.Employee;
import mx.entity.PageBean;
import mx.service.CompanyService;
import mx.utils.DateJsonValueProcessor;
import mx.utils.ResponseUtil;
import mx.utils.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 * 公司controller
 * 
 * @author wkk
 * 
 */
@Controller
@RequestMapping("/company")
public class CompanyController {
	@Resource
	private CompanyService companyService;

	@RequestMapping("/list")
	public String list(
			@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows,
			Company company, HttpServletResponse response) throws Exception {
		PageBean pageBean = new PageBean(Integer.parseInt(page),
				Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", StringUtil.formatLike(company.getName()));
		map.put("father", StringUtil.formatLike(company.getFather()));
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		List<Company> companyList = companyService.list(map);
		long totatl = companyService.getTotal(map);
		JSONObject result = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(companyList, jsonConfig);
		result.put("rows", jsonArray);
		result.put("total", totatl);
		ResponseUtil.write(response, result);
		return null;
	}

	/**
	 * 根据id删除公司信息
	 * 
	 * 
	 */
	@RequestMapping(value = "/delete")
	public String deleteComById(@RequestParam(value = "ids", required = false) String ids, HttpServletResponse response)
			throws Exception {
		String[] id = ids.split(",");

		for (String comId : id) {
			companyService.delete(Integer.parseInt(comId));
		}

		JSONObject result = new JSONObject();
		result.put("success", true);
		ResponseUtil.write(response, result);
		return null;
	}

	/**
	 * 增加公司（选择性填入参数）
	 * 
	 */
	@RequestMapping("/save")
	public String save(Company company, HttpServletResponse response) throws Exception {
		int resultTotal = 0;
		JSONObject result = new JSONObject();
		if (company.getId() == null) {
			resultTotal = companyService.add(company);
		} else {
			resultTotal = companyService.update(company);
		}
		if (resultTotal > 0) {
			result.put("success", true);
		} else {
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
	}
}
